package com.cade.agriculturemall.view.shoppingCar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseFragment;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShopcarsModel;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.utils.RefreshLayout;
import com.cade.agriculturemall.view.classify.goodsdetail.GoodsDetailActivity;
import com.cade.agriculturemall.view.refresh.OnRefreshListener;
import com.cade.agriculturemall.view.shoppingCar.settlement.SettlementActivity;
import com.cade.agriculturemall.widget.EmptyLayout;
import com.wenld.smoothcheckbox.SmoothCheckBox;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lobby on 2017/11/16.
 */

public class ShoppingCarFragment extends BaseFragment<ShoppingCarContract.IPesenter> implements ShoppingCarContract.IView, OnRefreshListener, ShopCarsExpandableListAdapter.MyClickListener {
    private List<ShopcarsModel> lists = new ArrayList<>();
    private ExpandableListView expandableListView;
    private ShopCarsExpandableListAdapter adapter;
    private Button btnEdit;
    private SmoothCheckBox btnSelectAll;
    boolean isEdit = true;
    private Button btnSettleme;
    private EmptyLayout mEmptyLayout;
    private TextView tvCountMoney, tvSettlement;
    private float num = 0;
    private int chooseGoods = 0;
    private RefreshLayout mRefreshLayout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int setupLayout() {
        return R.layout.layout_shopping_car;
    }

    @Override
    public void setupView() {
        mRefreshLayout = (RefreshLayout) getView().findViewById(R.id.shopping_car_refresh);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setLoadMoreEnable(false);
        mEmptyLayout = (EmptyLayout) getView().findViewById(R.id.shopping_car_emptyLayout);
        expandableListView = (ExpandableListView) getView().findViewById(R.id.shopping_car_expandableListView);
        adapter = new ShopCarsExpandableListAdapter(this, getContext(), expandableListView, this);
        expandableListView.setGroupIndicator(null);
        expandableListView.setAdapter(adapter);
        btnEdit = (Button) getView().findViewById(R.id.shopping_car_btn_edit);
        btnSelectAll = (SmoothCheckBox) getView().findViewById(R.id.cb_select_all);
        btnSelectAll.setOnCheckedChangeListener(checkedChangeListener);
        btnEdit.setOnClickListener(onClick);
        tvCountMoney = (TextView) getView().findViewById(R.id.tv_all_money);
        tvSettlement = (TextView) getView().findViewById(R.id.btn_settlement);
        adapter.setOnPlayClickListener(onItemDeleteClick);
        adapter.setIsAllSelectedListener(new ShopCarsExpandableListAdapter.IsAllSelectedListener() {
            @Override
            public void onSelectedChanged(Boolean allSelected) {
                btnSelectAll.setOnCheckedChangeListener(null);
                btnSelectAll.setChecked(allSelected);
                btnSelectAll.setOnCheckedChangeListener(checkedChangeListener);
                countPrice();
            }
        });

        btnSettleme = (Button) getView().findViewById(R.id.btn_settlement);
        btnSettleme.setOnClickListener(onClick);
        adapter.setChildOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int section = (int) v.getTag(R.id.section);
                int position = (int) v.getTag(R.id.position);
                String objectId = lists.get(section).getGoodBeanList().get(position).getProId().getObjectId();
                Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
                if (objectId != null) {
                    intent.putExtra("objectId", objectId);
                    startActivity(intent);
                }
            }
        });
    }


    /**
     * 结算金额
     */
    @Override
    public void countPrice() {
//        isEdit = true;
//        edit();
        num = 0;
        chooseGoods = 0;//选择的商品项个数
        for (ShopcarsModel model : adapter.getList()) {
            for (ShoppingCarsEntity e : model.getGoodBeanList()) {
                if (e.isSelected() && e.getProId().getPriceNew() != null) {
                    chooseGoods = ++chooseGoods;
                    num += Float.parseFloat((Float.parseFloat(e.getProId().getPriceNew()) * e.getQuantitate() + ""));
                }
            }
        }
        tvCountMoney.setText("￥" + num + "元");
        tvSettlement.setText(chooseGoods == 0 ? "结算" : "结算（" + chooseGoods + "）");
    }

    private SmoothCheckBox.OnCheckedChangeListener checkedChangeListener = new SmoothCheckBox.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(SmoothCheckBox checkBox, boolean isChecked) {
            isEdit = true;
            for (ShopcarsModel model : adapter.getList()) {
                model.setAllSelect(isChecked);
                for (ShoppingCarsEntity e : model.getGoodBeanList()) {
                    e.setSelected(isChecked);
                }
            }
            adapter.notifyDataSetChanged();
            countPrice();

        }
    };

    View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.shopping_car_btn_edit:
                    edit();
                    break;
                case R.id.btn_settlement:
                    settlement();
                    break;
            }
        }
    };

    //      结算跳转
    private void settlement() {
//    判断是否选择商品
        List<ShoppingCarsEntity> goodsSettlement = new ArrayList<>();
        boolean hasGoods = false;
        for (ShopcarsModel model : adapter.getList()) {
            for (ShoppingCarsEntity e : model.getGoodBeanList()) {
                if (e.isSelected() == true) {
                    hasGoods = true;
                    goodsSettlement.add(e);
                }
            }
        }
        if (!hasGoods) {
            Toast.makeText(getActivity(), "您还没有选择宝贝哦~", Toast.LENGTH_SHORT).show();
        } else {
            Intent settlementIntent = new Intent(getActivity(), SettlementActivity.class);
            settlementIntent.putExtra("num", num);
            settlementIntent.putParcelableArrayListExtra("goodsSettlement", (ArrayList<? extends Parcelable>) goodsSettlement);
            startActivity(settlementIntent);
        }
    }

    /**
     * 编辑商品数量
     */

    private void edit() {
        if (isEdit) {
            isEdit = false;
            btnEdit.setText("完成");
            for (int i = 0; i < lists.size(); i++) {
                for (int n = 0; n < lists.get(i).getGoodBeanList().size(); n++) {
                    lists.get(i).getGoodBeanList().get(n).setIsedit(true);
                }
            }
        } else {
            isEdit = true;
            btnEdit.setText("编辑");
            for (int i = 0; i < lists.size(); i++) {
                for (int n = 0; n < lists.get(i).getGoodBeanList().size(); n++) {
                    lists.get(i).getGoodBeanList().get(n).setIsedit(false);
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setupEvent() {
    }

    @Override
    public void setupData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        mEmptyLayout.loading();
        mPresenter.downLoadShopCars();
    }

    @Override
    public ShoppingCarContract.IPesenter setupPresenter() {
        return new ShoppingCarPresenter(this);
    }

    @Override
    public void onLoadShopCars(List<ShopcarsModel> list, int size) {
        mRefreshLayout.endRefreshing();
        if (size == 0) {
            mEmptyLayout.empty();
            adapter.notifyDataSetChanged();
        } else {
            mEmptyLayout.reset();
            lists = list;
            adapter.setList(list);
            adapter.notifyDataSetChanged();
        }
        TextView title = (TextView) getView().findViewById(R.id.toolbar_shopcar_title);
        title.setText("购物车（" + size + "）");
        countPrice();
        btnSelectAll.setChecked(false);
    }

    //    删除商品item
    ShopCarsExpandableListAdapter.OnItemDeleteListener onItemDeleteClick = new ShopCarsExpandableListAdapter.OnItemDeleteListener() {
        @Override
        public void onItemClick(int position) {
            mEmptyLayout.loading();
            mPresenter.downLoadShopCars();
            countPrice();
            adapter.notifyDataSetChanged();
        }
    };

    public void setEdit(boolean edit) {
        isEdit = edit;
    }

    @Override
    public void onStartRefresh() {
        mPresenter.downLoadShopCars();
    }

    public List<OrderEntity> getUnnPayEntity() {
        return null;
    }

    public List<OrderEntity> getNoDeliveEntity() {
        return null;
    }

    public List<OrderEntity> getFinishEntity() {
        return null;
    }

    @Override
    public void clickListener(View v) {
        countPrice();
    }
}
